#include "buzzer.h"
// PC1
BuzzerControl_t buzzer_ctrl = {0};
uint8_t buzzer_state = 0; // 0为关闭，1为开启
uint16_t buzzer_on_time = 0;

void buzzer_on(void)
{
    buzzer_on_time = uwTick;
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_12, GPIO_PIN_SET);
    buzzer_state = 1;
}
void buzzer_off(void)
{
    HAL_GPIO_WritePin(GPIOE, GPIO_PIN_12, GPIO_PIN_RESET);
    buzzer_on_time = 0;
    buzzer_state = 0;
}

void buzzer_beep(uint8_t times, uint32_t on_ms, uint32_t off_ms)
{
    buzzer_ctrl.is_running = 1;
    buzzer_ctrl.state = 0; // 先关
    buzzer_ctrl.count = 0;
    buzzer_ctrl.target_count = times;
    buzzer_ctrl.on_time = on_ms;
    buzzer_ctrl.off_time = off_ms;
    buzzer_ctrl.last_tick = uwTick;
    buzzer_off();
}


void buzzer_run_proc(void)
{
    if (!buzzer_ctrl.is_running) return;

    if (buzzer_ctrl.state == 0) { // 目前是关，判断是否该开
        if ((uwTick - buzzer_ctrl.last_tick) >= buzzer_ctrl.off_time) {
            if (buzzer_ctrl.count < buzzer_ctrl.target_count) {
                buzzer_on();
                buzzer_ctrl.state = 1;
                buzzer_ctrl.last_tick = uwTick;
            } else {
                buzzer_ctrl.is_running = 0; // 完成任务
            }
        }
    } else { // 目前是开，判断是否该关
        if ((uwTick - buzzer_ctrl.last_tick) >= buzzer_ctrl.on_time) {
            buzzer_off();
            buzzer_ctrl.state = 0;
            buzzer_ctrl.last_tick = uwTick;
            buzzer_ctrl.count++;
        }
    }
}